<template>
  <div>
    <TopTitle>
      <template #title>{{sectName}}</template>
      <template #search>
        <div class="save-tip">
          {{ saveLoading ? '正在保存中' : `最近保存：${dayjs(lastSaveTime).format('HH:mm')}` }}
        </div>
      </template>
    </TopTitle>

    <el-scrollbar class="scrollbar">
      <div class='chapterMain' v-loading='loading'>
        <div class='item'>
          <PubEditor
            :editContent='detail.content'
            @editContentEnv='editContentEnv'
            placeholder='请认真填写教学设计...'
          ></PubEditor>
        </div>
        <div class='item'>
          <OtherBigFile :fileArr='detail.minioInfos' ref='OtherBigFileRef'
                        @fileArrChange='fileArrChange'></OtherBigFile>
        </div>
      </div>
    </el-scrollbar>

    <SaveBtn
      :saveState='saveState'
      :saveText='saveText'
      :saveLoading='saveLoading'
      @click='()=> handleSaveDetails(true,true)'
    >
    </SaveBtn>

    {{detail}}
  </div>
</template>

<script setup>
import {teachDesignDetail,upDesignDetail} from "@/api/chapter"
import TopTitle from '@/components/TopTitle.vue';
import PubEditor from '@/components/PubEditor/index.vue';
// import SaveBtn from '@/components/SaveBtn.vue';
import OtherBigFile from '@/components/OtherBigFile/index.vue';
import {ElMessage} from 'element-plus';
import {useViewScrollbarHeight} from "@/utils/tools";
import {onBeforeRouteLeave} from "vue-router";
import dayjs from "dayjs";

const props = defineProps({
  nodeid: {
    type: String,
    default: '',
  },
  sectName:{
    type:String,
    default:''
  }
});


const emits = defineEmits(['save', 'backNode'])

const loading = ref(true);
const saveLoading = ref(false);
const saveState = ref(false);
const hisContent = ref();
const hisFiles = ref('[]');
const OtherBigFileRef = ref(null);
const lastSaveTime = ref(Date.now())
const olddetail=ref()
const currNodeId = ref(props.nodeid)
const detail = ref({
    content:"",
    minioInfos:[]
});

// 自动保存计时器，内容有变动时每秒定时步进1，为5时触发自动保存，保存后重置为0
// let autoSaveTimer = ref(0)
// const interval = setInterval(() => {
//   if (saveState.value) autoSaveTimer.value++
// }, 1000)

const {innerScrollbarHeightStyle} = useViewScrollbarHeight()

const saveText = ref('保存教学')


//获取每小节教学设计的详细内容
const getChapterShow = () => {
  loading.value = true;
  teachDesignDetail(unref(currNodeId)).then(res => {
    console.log(res.data);
    olddetail.value=res.data
    if(res.data){
      res.data.content = res.data.content || '';
      res.data.minioInfos =JSON.parse(res.data.minioInfos) || [];
      detail.value = res.data;
      hisContent.value = res.data.content;
      hisFiles.value = JSON.stringify(res.data.minioInfos);
      return
    }
    detail.value.content='',
    detail.value.minioInfos=[]

  }).finally(() => {
    loading.value = false;
  });
};

//获取富文本返回的内容
const editContentEnv = (e) => {
  // autoSaveTimer.value = 0
  detail.value.content = e;
};

//保存详情内容
const handleSaveDetails = (refresh = false, notice = false) => {

  console.log(olddetail.value);

  // 如果教学设计的内容为空走保存，如果不为空走更新
  if(olddetail.value){
    console.log("更新教学设计");
    // let upData={
    //   id: "1778311877757079554",
    //   sectionId: "1767078758588567817",
    //   content: "1242786394786231894567789364598689327485富文本内容666 ",
    //   minioFiles:
    // }

    upDesignDetail().then(res=>{
      console.log(res);
    })

    return
  }

  if (!detail.value.content || detail.value.content === '<p><br></p>') {
    if (notice === true) ElMessage.error('请认真填写作业要求');
    return
  }
  const saveData = {
    sectionId:unref(currNodeId),
    content:detail.value.content,
    minioFiles:detail.value.minioInfos
  }
  saveLoading.value = true
  saveState.value = true
  // 新增教学设计
  upDesignDetail(JSON.stringify(saveData)).then(res => {
    if (res.code !== 200) return ElMessage.error(res.msg);
    saveState.value = false;
    lastSaveTime.value = Date.now()
    if (notice === true) ElMessage.success('保存成功')
    if (refresh !== false) emits('save')
    else {
      hisContent.value = unref(detail).content
      hisFiles.value = JSON.stringify(unref(detail).minioInfos)
    }
  }).finally(() => {
    saveLoading.value = false;
    // autoSaveTimer.value = 0
  })
};


//大附件内容改变的时候
const fileArrChange = (e) => {
  console.log(e);
  detail.value.minioInfos = e;
};

// 热键保存事件
const handleSaveHotKey = (e) => {
  // ctrl + s
  if ((e.ctrlKey || e.metaKey) && e.keyCode === 83) {
    e.preventDefault()
    if (loading.value) return false
    if (saveState.value === false) {
      ElMessage.success('已保存')
      lastSaveTime.value = Date.now()
      return false
    }
    saveState.value = true
    handleSaveDetails(false, true)
    return false
  }
}

// 页面卸载事件
const handleUnload = (event) => {
  if (loading.value) return
  if (saveState.value === false) return
  event.preventDefault();
  event.returnValue = "";
  return ''
}

// 路由离开事件
const handleRouteLeave = () => {
  let result = true
  if (loading.value === true) result = false
  if (saveState.value === true) result = window.confirm('内容还未保存是否要离开？')
  if (!result) emits('backNode', unref(currNodeId))
  return result
}

getChapterShow();

watch(() => props.nodeid, () => {
  // autoSaveTimer.value = 0

  console.log(handleRouteLeave());
  if (props.nodeid === unref(currNodeId)) return
  if (handleRouteLeave()) {
    currNodeId.value = props.nodeid
    getChapterShow()
  }
});

// 自动保存
// watch(autoSaveTimer, (time) => {
//   if (time >= 5) {
//     if (loading.value) return
//     if (saveLoading.value) return
//     if (saveState.value === false) return;
//     handleSaveDetails(false, false)
//   }
// })

watch(() => detail.value.content, (nv) => {
  saveState.value = !(nv === hisContent.value || nv === '<p><br></p>');
});

watch(() => detail.value.minioInfos, (nv) => {
  saveState.value = JSON.stringify(nv) !== hisFiles.value;
}, {
  deep: true,
});

window.addEventListener("beforeunload", handleUnload)
document.addEventListener('keydown', handleSaveHotKey)

onBeforeRouteLeave(() => {
  return handleRouteLeave()
})

onUnmounted(() => {
  // autoSaveTimer.value = 0
  // clearInterval(interval)
  window.removeEventListener('beforeunload', handleUnload)
  document.removeEventListener('keydown', handleSaveHotKey)
})

</script>

<style lang='scss' scoped>
@use '@/assets/styles/vars.module' as *;

.save-tip {
  font-size: 14px;
  color: #000;
  opacity: 0.48;
}

.scrollbar {
  height: v-bind(innerScrollbarHeightStyle);
}

.chapterMain {
  width: $rich-view-width;
  padding-left: 0;
  padding-right: 0;
  margin: 0 auto;

  .item {
    width: 100%;
    padding-bottom: 40px;
  }
}
</style>
